import router from '@renderer/router'
import { useOperationConfiguration } from '@renderer/stores/operationConfiguration'
import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'

const http = axios.create({
  baseURL: VITE_APP_BASE_URL,
  timeout: 60000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  }
})

const operationConfigurationStore = useOperationConfiguration()
const { token } = storeToRefs(operationConfigurationStore)
http.interceptors.request.use((config) => {
  if (token.value) {
    // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    config.headers['Authorization'] = token.value
  }
  return config
})

// 请求后拦截
http.interceptors.response.use(
  (res) => {
    const headers = JSON.stringify(res.headers)
    const headers_data = JSON.parse(headers)
    const token = headers_data['x-auth-token']
    if (token) {
      //将续期的TOKEN存起来
      operationConfigurationStore.setToken(token)
    }
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200
    if (code === 200) {
      return Promise.resolve(res.data)
    } else if (code === 403 || code === 401) {
      router.replace('/login')
      return Promise.reject(res.data.msg)
    } else if (code === 500) {
      ElMessage.warning({
        message: res.data.msg
      })
      return Promise.reject(res.data)
    }

    // 二进制数据则直接返回
    if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
      return res.data
    }

    // 请求错误 获取错误信息
    const message = res.data.message
    return Promise.reject(new Error(code + message))
  },
  (error) => {
    let { message } = error
    if (message == 'Network Error') {
      message = '后端接口连接异常'
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时'
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常'
    }
    ElMessage({
      message: message,
      type: 'error',
      duration: 3 * 1000,
      showClose: true
    })
    return Promise.reject(error)
  }
)

export interface BuiAxios extends AxiosInstance {
  /**
   * content-type使用JSON
   */
  postOrJson<T = any, R = AxiosResponse<T>, D = any>(
    url: string,
    data?: D,
    config?: AxiosRequestConfig<D>
  ): Promise<R>
  putOrJson<T = any, R = AxiosResponse<T>, D = any>(
    url: string,
    data?: D,
    config?: AxiosRequestConfig<D>
  ): Promise<R>
  deleteOrJson<T = any, R = AxiosResponse<T>, D = any>(
    url: string,
    data?: D,
    config?: AxiosRequestConfig<D>
  ): Promise<R>
}

;(http as BuiAxios).postOrJson = (url, params, config) => {
  return http.post(url, params, {
    headers: {
      'Content-Type': 'application/json'
    },
    ...config
  })
}
;(http as BuiAxios).putOrJson = (url, params, config) => {
  return http.put(url, params, {
    headers: {
      'Content-Type': 'application/json'
    },
    ...config
  })
}
;(http as BuiAxios).deleteOrJson = (url, params, config) => {
  return http.delete(url, {
    data: params,
    headers: {
      'Content-Type': 'application/json'
    },
    ...config
  })
}

export default http as BuiAxios
